//
//  UITableView.swift
//  
//
//  Created by tangbl93 on 2021/1/12.
//

import UIKit

// MARK: UITableView
public extension UITableView {
    
    /// reloadData with completion block
    func yx_reloadData(_ completion: @escaping VoidClosure) {
        UIView.animate(withDuration: 0, animations: {
            self.reloadData()
        }, completion:{ _ in
            completion()
        })
    }
    
    /// turnoff Self-Sizing
    /// https://jundongwu.com/p/e0dc33b4.html
    func yx_turnoffSelfSizing () {
        estimatedRowHeight = 0
        estimatedSectionHeaderHeight = 0
        estimatedSectionFooterHeight = 0
    }
    
    /// turnoff Self-Sizing
    static func yx_turnoffSelfSizing () {
        UITableView.appearance().estimatedRowHeight = 0
        UITableView.appearance().estimatedSectionFooterHeight = 0
        UITableView.appearance().estimatedSectionHeaderHeight = 0
    }
}

// MARK: IndexPathable
extension UITableView: IndexPathable {}
public extension IndexPathable where Self: UITableView {
    
    /// first indexPath, nil if no row
    var yx_firstIndexPath: IndexPath? {
        let indexPath = IndexPath(row: 0, section: 0)
        
        guard indexPath.section < numberOfSections
              && indexPath.row < numberOfRows(inSection: indexPath.section) else {
            return nil
        }
        
        return indexPath
    }
    
    /// last indexPath
    var yx_lastIndexPath: IndexPath? {
        guard numberOfSections > 0 else { return nil }
        let lastSection = numberOfSections - 1
                
        let lastRow = numberOfRows(inSection: lastSection) - 1
        guard lastRow > 0 else { return nil }
        
        return IndexPath(row: lastRow, section: lastSection)
    }
    
    /// indexPaths for visibleCells
    var yx_visibleIndexPaths:[IndexPath] {
        return indexPathsForVisibleRows ?? []
    }
}

